#!/bin/sh /etc/rc.common
# Copyright (C) 2014 nanpuyue <nanpuyue@gmail.com>

STOP=01
SERVICE_WRITE_PID=1
SERVICE_DAEMONIZE=1

append_params() {
	local p; local v; local s="$1"; shift
	for p in $*; do
		config_get v "$s" "$p"
		[ -n "$v" ] && (
			p=$(echo "$p" | sed -e 's|_|-|g');
			echo "$p=$v" >> $config_file
			)
	done
}

section_enabled() {
	local result
	config_get_bool result "$1" 'enabled' 0
	[ $result -eq 1 ]
}

option_disabled() {
	local result
	config_get_bool result "$1" "$2" 1
	[ $result -eq 0 ]
}

start_instance() {
	local s="$1"
	local user

	section_enabled "$s" || return 1

	config_get config_dir "$s" 'config_dir' '/var/etc/aria2'
	config_get user "$s" 'user'

	config_file="$config_dir/aria2.conf"
	session_file="$config_dir/aria2.session"
	dht_file="$config_dir/dht.dat"
	[ -d "$config_dir" ] || {
		mkdir -m 0755 -p "$config_dir"
		touch "$config_file"
		[ -z "$user" ] || chown -R $user $config_dir
	}
	touch "$session_file"

	echo -e "enable-rpc=true\nrpc-allow-origin-all=true\nrpc-listen-all=true\nquiet=true" > $config_file
	echo -e "continue=true\ninput-file=$session_file\nsave-session=$session_file" >> $config_file
	option_disabled "$s" 'enable_dht' || echo "dht-file-path=$dht_file" >> $config_file

	append_params "$s" \
		file_allocation bt_enable_lpd enable_dht rpc_user rpc_passwd rpc_listen_port dir bt_tracker disk_cache \
		max_overall_download_limit max_overall_upload_limit max_download_limit max_upload_limit max_concurrent_downloads \
		max_connection_per_server min_split_size split save_session_interval follow_torrent listen_port bt_max_peers

	SERVICE_UID="$user" \
	service_start /usr/bin/aria2c --conf-path="$config_file"
}

enabled() {
	# always enabled, by aria2delaystarter
	return 0
}

start() {
	config_load 'aria2'
	config_foreach start_instance 'aria2'
}

stop() {
	service_stop /usr/bin/aria2c
}
